﻿using DubaiCoffee.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows;
using Rectangle = System.Drawing.Rectangle;

namespace DubaiCoffee
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public static bool isMake = true;
        public static double MakingTypes = 0;
        public static string img_path = "";
        public static string IPorPortUrl = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"\IPorPortMessage.txt";
        public static string WarnPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"Warn";
        public static string BreakPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"BreakDowm";
        public static string Printer = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"Printer";
        public static double SugarInit1 = 3;
        public static double SugarInit2 = 3;
        public static double SugarInit3 = 3;
        public MainWindow()
        {
            InitializeComponent();
        }
        public static string EmailError()
        {
            try
            {
                string msg = "<style>table{ border: 1px solid black; border-collapse: collapse; }table td{border: 1px solid #000000; padding: 5px 15px;font-size:14px;}</style><table>";
                if (WuLiaoCoffeeSel.Instance.CoffeeBean_Sel_Bol)
                    msg += "<tr><td style='font-weight:bold;'>CoffeeBean</td><td>adequate materials</td></tr>";
                else
                    msg += "<tr><td style='font-weight:bold;'>CoffeeBean</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                if (!WuLiaoCoffeeSel.Instance.Milk_Sel_Bol)
                    msg += "<tr><td style='font-weight:bold;'>Milk</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                else
                    msg += "<tr><td style='font-weight:bold;'>Milk</td><td>adequate materials</td></tr>";
                if (WuLiaoCoffeeSel.Instance.CupFeed1_Sel_Bol)
                    msg += "<tr><td style='font-weight:bold;'>Cup1</td><td>adequate materials</td></tr>";
                else
                    msg += "<tr><td style='font-weight:bold;'>Cup1</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                //if (WuLiaoCoffeeSel.Instance.CupFeed2_Sel_Bol)
                //    msg += "<tr><td style='font-weight:bold;'>Cup2</td><td>adequate materials</td></tr>";
                //else
                //    msg += "<tr><td style='font-weight:bold;'>Cup2</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                if (WuLiaoCoffeeSel.Instance.YBJ_Water)
                    msg += "<tr><td style='font-weight:bold;'>Water</td><td>adequate materials</td></tr>";
                else
                    msg += "<tr><td style='font-weight:bold;'>Water</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                if (WuLiaoCoffeeSel.Instance.ZBJYBJ_Water)
                    msg += "<tr><td style='font-weight:bold;'>Ice Water</td><td>adequate materials</td></tr>";
                else
                    msg += "<tr><td style='font-weight:bold;'>Ice Water</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                if (WuLiaoCoffeeSel.Instance.GT1_Sel_Bol)
                    msg += "<tr><td style='font-weight:bold;'>sugar1</td><td>adequate materials</td></tr>";
                else
                    msg += "<tr><td style='font-weight:bold;'>sugar1</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                if (WuLiaoCoffeeSel.Instance.GT2_Sel_Bol)
                    msg += "<tr><td style='font-weight:bold;'>sugar2</td><td>adequate materials</td></tr>";
                else
                    msg += "<tr><td style='font-weight:bold;'>sugar2</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                if (WuLiaoCoffeeSel.Instance.GT3_Sel_Bol)
                    msg += "<tr><td style='font-weight:bold;'>sugar3</td><td>adequate materials</td></tr>";
                else
                    msg += "<tr><td style='font-weight:bold;'>sugar3</td><td style='color:#FF0000;'>Lack of material</td></tr>";
                //if (!IsMsgError)
                //    msg += "<tr><td style='font-weight:bold;'>Coffee Maker</td><td>Ready</td></tr>";
                //else
                //    msg += "<tr><td style='font-weight:bold;'>Coffee Maker</td><td style='color:#FF0000;'>NotReady</td></tr>";
                msg += "</table>";
                return msg;
            }
            catch (Exception)
            {
                return "";
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!File.Exists(IPorPortUrl))
                {
                    using (FileStream stream = File.Create(IPorPortUrl))
                    {
                        stream.Close();
                        stream.Dispose();
                        IPorPortInfo porPortInfo1 = IPorPortInfo.Instance;
                        File.WriteAllText(IPorPortUrl, JsonConvert.SerializeObject(porPortInfo1));
                    }
                }

                else
                {
                    var dd = File.ReadAllText(IPorPortUrl);
                    var porPortInfo = JsonConvert.DeserializeObject<IPorPortInfo>(File.ReadAllText(IPorPortUrl));
                    IPorPortInfo.Instance.CoffeeIP = porPortInfo.CoffeeIP;
                    IPorPortInfo.Instance.CoffeePort = porPortInfo.CoffeePort;
                    IPorPortInfo.Instance.RobotIPLeft = porPortInfo.RobotIPLeft;
                    IPorPortInfo.Instance.RobotIPRight = porPortInfo.RobotIPRight;
                    IPorPortInfo.Instance.PortName = porPortInfo.PortName;
                    IPorPortInfo.Instance.PrinterCoffeeIP = porPortInfo.PrinterCoffeeIP;
                    IPorPortInfo.Instance.PrinterCofferPort = porPortInfo.PrinterCofferPort;
                    IPorPortInfo.Instance.EWMPortName = porPortInfo.EWMPortName;
                    IPorPortInfo.Instance.ZBPortName = porPortInfo.ZBPortName;
                    IPorPortInfo.Instance.CoffeePortName = porPortInfo.CoffeePortName;
                    IPorPortInfo.Instance.SugarInit1 = porPortInfo.SugarInit1;
                    IPorPortInfo.Instance.SugarInit2 = porPortInfo.SugarInit2;
                    IPorPortInfo.Instance.SugarInit3 = porPortInfo.SugarInit3;
                    MainWindow.SugarInit1 = porPortInfo.SugarInit1;
                    MainWindow.SugarInit2 = porPortInfo.SugarInit2;
                    MainWindow.SugarInit3 = porPortInfo.SugarInit3;
                    WuLiaoCoffeeSel.Instance.SugarInit1 = porPortInfo.SugarInit1;
                    WuLiaoCoffeeSel.Instance.SugarInit2 = porPortInfo.SugarInit2;
                    WuLiaoCoffeeSel.Instance.SugarInit3 = porPortInfo.SugarInit3;
                }
                if (!Directory.Exists(WarnPath))
                {
                    Directory.CreateDirectory(WarnPath);
                }
                if (!Directory.Exists(WarnPath + @"\" + DateTime.Now.ToString("yyyy")))
                {
                    Directory.CreateDirectory(WarnPath + @"\" + DateTime.Now.ToString("yyyy"));
                }
                try
                {
                    Directory.Delete(WarnPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.AddMonths(-1).ToString("MM"), true);
                }
                catch (Exception)
                {
                }
                if (!Directory.Exists(WarnPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM")))
                {
                    Directory.CreateDirectory(WarnPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM"));
                }
                if (!Directory.Exists(WarnPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd")))
                {
                    Directory.CreateDirectory(WarnPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd"));
                }
                WarnPath = WarnPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd");
                if (!Directory.Exists(BreakPath))
                {
                    Directory.CreateDirectory(BreakPath);
                }
                if (!Directory.Exists(BreakPath + @"\" + DateTime.Now.ToString("yyyy")))
                {
                    Directory.CreateDirectory(BreakPath + @"\" + DateTime.Now.ToString("yyyy"));
                }
                try
                {
                    Directory.Delete(BreakPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.AddMonths(-1).ToString("MM"), true);
                }
                catch (Exception)
                {
                }
                if (!Directory.Exists(BreakPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM")))
                {
                    Directory.CreateDirectory(BreakPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM"));
                }
                if (!Directory.Exists(BreakPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd")))
                {
                    Directory.CreateDirectory(BreakPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd"));
                }
                BreakPath = BreakPath + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd");
                if (!Directory.Exists(Printer))
                {
                    Directory.CreateDirectory(Printer);
                }
                if (!Directory.Exists(Printer + @"\" + DateTime.Now.ToString("yyyy")))
                {
                    Directory.CreateDirectory(Printer + @"\" + DateTime.Now.ToString("yyyy"));
                }
                try
                {
                    Directory.Delete(Printer + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.AddMonths(-1).ToString("MM"), true);
                }
                catch (Exception)
                {
                }
                if (!Directory.Exists(Printer + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM")))
                {
                    Directory.CreateDirectory(Printer + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM"));
                }
                try
                {
                    Directory.Delete(Printer + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.AddDays(-1).ToString("dd"), true);
                }
                catch (Exception)
                {
                }
                if (!Directory.Exists(Printer + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd")))
                {
                    Directory.CreateDirectory(Printer + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd"));
                }
                Printer = Printer + @"\" + DateTime.Now.ToString("yyyy") + @"\" + DateTime.Now.ToString("MM") + @"\" + DateTime.Now.ToString("dd");
                Thread thr3 = new Thread(SocketClients.Instance.socketclient);
                thr3.IsBackground = true;
                thr3.Start();
                Thread thr = new Thread(IOMsg.Instance.IOSerial_Thr);
                thr.IsBackground = true;
                thr.Start();
                Thread thr1 = new Thread(coffeeMsg.Instance.IOSerial_Thr);
                thr1.IsBackground = true;
                thr1.Start();
                //Thread thr4 = new Thread(EWMMsg.Instance.IOSerial_Thr);
                //thr4.IsBackground = true;
                //thr4.Start();
                Thread thr5 = new Thread(PwebSockets.Instance.Printer_Thr);
                thr5.IsBackground = true;
                thr5.Start();
                Thread thr6 = new Thread(IceMakingMsg.Instance.IOSerial_Thr);
                thr6.IsBackground = true;
                thr6.Start();
            }
            catch (Exception)
            {
                return;
            }
        }
        /// <summary>
        /// 全部订单查询
        /// </summary>
        public static void MessageShow()
        {
            while (true)
            {
                try
                {
                    Device device = new Device();
                    string lists = JsonConvert.SerializeObject(device);
                    var data = HttpMsg.Instance.deviceOrderQueueListMsg(lists);

                    if (data != null)
                    {
                        if (isMake)
                        {
                            var msglist = JsonConvert.DeserializeObject<HTTPMsg>(data);
                            if (msglist != null)
                            {
                                if (msglist.data.ToString().Length > 10)
                                {
                                    var list = JsonConvert.DeserializeObject<List<deviceOrderQueueList>>(msglist.data.ToString());
                                    if (list.Count > 0)
                                    {
                                        if (isMake)
                                        {
                                            if (list.Count > 0)
                                            {
                                                var ddd = list.FirstOrDefault(a => a.typeList2.Count > 0);
                                                if (ddd == null) continue;
                                                if (ddd.typeList2.Count > 0)
                                                {
                                                    var make = ddd.typeList2.FirstOrDefault(a => a.status == "3" || a.status == "4");
                                                    if (make != null)
                                                    {
                                                        if (make.jsonCodeVal.Length > 4)
                                                        {
                                                            var coffeecode = JsonConvert.DeserializeObject<List<specification>>(make.jsonCodeVal);
                                                            if (coffeecode.Count > 0)
                                                            {
                                                                var coffeeID = coffeecode.FirstOrDefault(a => a.classCode != "");
                                                                if (coffeeID != null)
                                                                {
                                                                    RobotOperate.CX_Start();
                                                                    Console.WriteLine(DateTime.Now.ToString() + "  cx5");
                                                                    if (RobotOperate.pstatus == JKTYPE.ProgramState.PROGRAM_RUNNING)
                                                                    {
                                                                        if (coffeeMsg.Instance.isBreakDown && coffeeMsg.Instance.isWarn)
                                                                            CoffeeMaking(coffeeID.classCode, make, ddd.orderNum);
                                                                        //CoffeeMaking("5003", null, "5003");
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception)
                {
                    //return;
                    Thread.Sleep(1000);
                }
            }

        }
        /// <summary>
        /// 取杯
        /// </summary>
        /// <param name="cupCode"></param>
        public static void QBMsg(int cupcode)
        {
            try
            {
                IOMsg.Instance.AllBol = false;
                Thread.Sleep(200);
                // if (cupcode == 2)
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJB1_UP);
                //else
                //    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJB2_UP);
                Thread.Sleep(200);
                while (true)
                {
                    Console.WriteLine("daojiebeidian1 " + DateTime.Now.ToString());
                    IOMsg.Instance.RobotBol = false;
                    Thread.Sleep(200);
                    //  if (cupcode == 2)
                    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DDLBQ1);
                    //else
                    //    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DDLBQ2);
                    Thread.Sleep(200);
                    if (IOMsg.Instance.RobotBol)
                    {
                        Thread.Sleep(200);
                        IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KFJ_Down);
                        Thread.Sleep(200);
                        IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KB_Down);
                        Thread.Sleep(200);
                        break;
                    }
                }
                Thread.Sleep(200);
                //if (cupcode == 2)
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.Drop_Cup_start);
                //else
                //    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.Drop_Cup2_start);
                Thread.Sleep(200);
                //  IOMsg.Instance.AllBol = true;
                //if (cupcode == 2)
                //{
                //while (WuLiaoCoffeeSel.Instance.LBQFK1_Bol) { Thread.Sleep(10); }
                //while (!WuLiaoCoffeeSel.Instance.LBQFK1_Bol) { Thread.Sleep(10); }
                //}
                //else
                //{
                //    while (WuLiaoCoffeeSel.Instance.LBQFK2_Bol) { Thread.Sleep(10); }
                //    while (!WuLiaoCoffeeSel.Instance.LBQFK2_Bol) { Thread.Sleep(10); }
                //}
                //  IOMsg.Instance.AllBol = false;
                // Thread.Sleep(100);
                //if (cupcode == 2)
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.Drop_Cup_end);
                //else
                //    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.Drop_Cup2_end);
                Thread.Sleep(1000);
                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JCJB_UP);
                Thread.Sleep(500);
                IOMsg.Instance.RobotBol = false;
                while (true)
                {
                    Thread.Sleep(100);
                    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DJBJC);
                    Thread.Sleep(100);
                    if (IOMsg.Instance.RobotBol)
                    {
                        break;
                    }
                }
                IOMsg.Instance.AllBol = true;
            }
            catch (Exception)
            {
                return;
            }
        }
        public static int CupCode(string code, int cupCode)
        {
            try
            {
                int coffeecode = 5001;
                switch (code)
                {
                    case "5001":
                        coffeecode = 5001;
                        break;
                    case "5002":
                        if (cupCode == 3)
                            coffeecode = 5024;
                        else
                            coffeecode = 5002;
                        break;
                    case "5003":
                        if (cupCode == 3)
                            coffeecode = 5020;
                        else
                            coffeecode = 5003;
                        break;
                    case "5005":
                        if (cupCode == 3)
                            coffeecode = 5017;
                        else
                            coffeecode = 5005;
                        break;
                    case "5103":
                        if (cupCode == 3)
                            coffeecode = 5116;
                        else
                            coffeecode = 5115;
                        break;
                    case "5105":
                        if (cupCode == 3)
                            coffeecode = 5109;
                        else
                            coffeecode = 5122;
                        break;
                }
                return coffeecode;
            }
            catch (Exception)
            {
                return 5001;
            }
        }
        public static void CoffeeMaking(string makecoffeeName, DeviceOrderQueue list, string orderNum, bool CoffeeBol = true)
        {
            try
            {
                //if (!coffeeMsg.Instance.isMaking)
                //{
                //    isMake = true;
                //    return;
                //}
                //if (!WuLiaoCoffeeSel.Instance.Milk_Sel_Bol || !WuLiaoCoffeeSel.Instance.Water_Sel_Bol)//|| !WuLiaoCoffeeSel.Instance.Water_Sel_Bol || !WuLiaoCoffeeSel.Instance.CupFeed_Sel_Bol
                //{
                //    isMake = true;
                //    return;
                //}
                if (!WuLiaoCoffeeSel.Instance.PushRodUP_Sel_Bol)
                {
                    CoffeeMakes.Instance.MakeMealMsg(orderNum);//出餐
                }
                isMake = false;
                int sugarCode = 0;
                int cupCode = 0;
                var msgs = JsonConvert.DeserializeObject<List<specification>>(list.jsonCodeVal);
                Console.WriteLine(DateTime.Now.ToString() + "  cx10" + list.jsonCodeVal);
                if (msgs != null)
                {
                    if (msgs.Any(a1 => a1.SugarCode != ""))
                    {
                        sugarCode = msgs.Any(a1 => a1.SugarCode == "1") ? 1 : msgs.Any(a1 => a1.SugarCode == "2") ? 2 : msgs.Any(a1 => a1.SugarCode == "3") ? 3 : 0;
                    }
                    if (msgs.Any(b => b.cupCode != ""))
                    {
                        cupCode = msgs.Any(b => b.cupCode == "1") ? 1 : msgs.Any(b => b.cupCode == "2") ? 2 : msgs.Any(b => b.cupCode == "3") ? 3 : 4;
                    }
                }
                while (true)
                {
                    EditDeviceOrderStatus status = new EditDeviceOrderStatus();
                    status.orderGoodsId = list.id;
                    status.orderId = list.orderId;
                    status.status = 4;
                    string lists = JsonConvert.SerializeObject(status);
                    var ddd1 = HttpMsg.Instance.editDeviceOrderStatusMsg(lists);
                    if (ddd1 != null)
                    {
                        if (ddd1 != "")
                        {
                            var list10 = JsonConvert.DeserializeObject<ListMsg>(ddd1);
                            if (list10 != null)
                            {
                                if (list10.code == "0" || list10.code == "1")
                                {
                                    Console.WriteLine(DateTime.Now.ToString() + "  cx25 " + ddd1);
                                    break;
                                }
                            }
                            Console.WriteLine(DateTime.Now.ToString() + "  cx25 " + ddd1);
                        }

                    }
                    Thread.Sleep(100);
                }
                //EditDeviceOrderStatus editDeviceOrder = new EditDeviceOrderStatus();
                //editDeviceOrder.status = 4;
                //editDeviceOrder.orderId = list.orderId;
                //editDeviceOrder.orderGoodsId = list.id;
                //var ddd = JsonConvert.SerializeObject(editDeviceOrder);
                //HttpMsg.Instance.editDeviceOrderStatusMsg(ddd);
                Thread.Sleep(500);
                ClientList clientList = new ClientList();
                clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                clientList.code = 10;
                clientList.IsMake = false;
                SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                //if (CoffeeBol)
                //{
                //    IOMsg.Instance.AllBol = false;
                //    IOMsg.Instance.RobotBol = false;
                //    Thread.Sleep(100);
                //    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DYD);
                //    Thread.Sleep(100);
                //    if (IOMsg.Instance.RobotBol)
                //    {
                //        IOMsg.Instance.QK();
                //    }
                //}
                int code = CupCode(makecoffeeName, cupCode);
                int MidCode = (int.TryParse(makecoffeeName, out int a) ? a : 5001) / 100;
                if (CoffeeBol)
                {
                    IOMsg.Instance.AllBol = false;
                    Thread.Sleep(200);
                    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJB1_UP);
                    if (MidCode == 52)
                    {
                        Thread.Sleep(200);
                        IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJB_UP);
                    }
                    if (MidCode == 51)
                    {
                        Thread.Sleep(200);
                        IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QDY_UP);
                    }
                    if (sugarCode == 1 || sugarCode == 2 || sugarCode == 3)
                    {
                        Thread.Sleep(200);
                        IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JGT_UP);
                    }
                    Thread.Sleep(200);
                    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KFJ_UP);
                    Thread.Sleep(1000);
                    QBMsg(cupCode);
                    Thread.Sleep(100);
                    IOMsg.Instance.AllBol = true;
                    Thread.Sleep(200);
                    while (true)
                    {
                        if (WuLiaoCoffeeSel.Instance.TakeCup_Sel_Bol)
                        {
                            IOMsg.Instance.AllBol = false;
                            Thread.Sleep(100);
                            IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBCG_UP);
                            Thread.Sleep(100);
                            if (sugarCode == 1 || sugarCode == 2 || sugarCode == 3)
                            {
                                //Thread.Sleep(200);
                                //IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JGT_UP);
                                IOMsg.Instance.RobotBol = false;
                                while (true)
                                {
                                    Thread.Sleep(200);
                                    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DDGTD);
                                    Thread.Sleep(200);
                                    if (IOMsg.Instance.RobotBol)
                                    {
                                        break;
                                    }
                                }
                            }
                            if (sugarCode == 1)
                            {
                                IOMsg.Instance.AllBol = false;
                                Thread.Sleep(200);
                                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.GT1_start);
                                Thread.Sleep(Convert.ToInt32(SugarInit1 * 1000));
                                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.GT1_end);
                                Thread.Sleep(200);
                                Thread.Sleep(1000);
                                // IOMsg.Instance.AllBol = true;
                            }
                            else if (sugarCode == 2)
                            {
                                IOMsg.Instance.AllBol = false;
                                Thread.Sleep(200);
                                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.GT2_start);
                                Thread.Sleep(Convert.ToInt32(SugarInit3 * 1000));
                                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.GT2_end);
                                Thread.Sleep(200);
                                Thread.Sleep(1000);
                            }
                            else if (sugarCode == 3)
                            {
                                IOMsg.Instance.AllBol = false;
                                Thread.Sleep(200);
                                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.GT3_start);
                                Thread.Sleep(Convert.ToInt32(SugarInit3 * 1000));
                                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.GT3_end);
                                Thread.Sleep(200);
                                Thread.Sleep(1000);
                            }
                            if (sugarCode == 1 || sugarCode == 2 || sugarCode == 3)
                            {
                                Thread.Sleep(1000);
                                IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_GTWC_UP);
                                Thread.Sleep(200);
                            }
                            if (MidCode == 52)
                            {
                                try
                                {

                                    IOMsg.Instance.RobotBol = false;
                                    while (true)
                                    {
                                        Thread.Sleep(200);
                                        IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_DJBD);
                                        Thread.Sleep(200);
                                        if (IOMsg.Instance.RobotBol)
                                        {
                                            break;
                                        }
                                    }
                                    IOMsg.Instance.AllBol = true;
                                    Thread.Sleep(200);
                                    IceMakingMsg.Instance.AllBol = false;
                                    Thread.Sleep(1000);
                                    IceMakingSerialPort.Instance.SerialSend(IceMakingModel.Instance.IceMaking);
                                    Thread.Sleep(1000);
                                    IceMakingMsg.Instance.AllBol = true;
                                    Thread.Sleep(4000);
                                    for (int i = 0; i < 2; i++)
                                    {
                                        if (!WuLiaoCoffeeSel.Instance.YBJ_Ice)
                                        {
                                            IceMakingMsg.Instance.AllBol = false;
                                            Thread.Sleep(1000);
                                            IceMakingSerialPort.Instance.SerialSend(IceMakingModel.Instance.IceMaking3);
                                            Thread.Sleep(1000);
                                            IceMakingMsg.Instance.AllBol = true;
                                            Thread.Sleep(2000);
                                        }
                                    }
                                    IOMsg.Instance.AllBol = false;
                                    Thread.Sleep(200);
                                    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JBWC_UP);
                                }
                                catch (Exception)
                                {
                                }
                            }
                            //if (sugarCode == 1 || sugarCode == 2 || sugarCode == 3)
                            //{
                            //    Thread.Sleep(200);
                            //    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QJKF_UP);
                            //    Thread.Sleep(200);
                            //}
                            Thread.Sleep(200);
                            IOMsg.Instance.AllBol = true;
                            Console.WriteLine(DateTime.Now.ToString() + "  cx17");
                            Console.WriteLine(DateTime.Now.ToString() + "  cx18");
                            //Thread.Sleep(1000);
                            break;
                        }
                        else
                        {
                            IOMsg.Instance.AllBol = false;
                            Thread.Sleep(200);
                            IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_KB_UP);
                            Thread.Sleep(200);
                            IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JCJB_Down);
                            Thread.Sleep(200);
                            IOMsg.Instance.AllBol = true;
                            Thread.Sleep(200);
                            QBMsg(cupCode);
                            IOMsg.Instance.AllBol = true;
                            Thread.Sleep(200);
                        }
                    }
                }
                int codes = int.TryParse(makecoffeeName, out int aa) ? aa : 5001;
                //Thread.Sleep(1000);
                CoffeeMakes.Instance.CoffeeMaking(codes, list.lhImgPath);
                //CoffeeMakes.Instance.CoffeeMaking(code, "");
                IOMsg.Instance.AllBol = false;
                Thread.Sleep(100);
                IOMsg.Instance.RobotBol = false;
                while (true)
                {
                    Thread.Sleep(100);
                    IOSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_CCWC);
                    Thread.Sleep(100);
                    if (IOMsg.Instance.RobotBol)
                    {
                        IOMsg.Instance.QK();
                        Thread.Sleep(200);
                        break;

                    }
                }
                CoffeeMakes.Instance.MakeMealMsg(orderNum);//出餐
                ClientList clientList1 = new ClientList();
                clientList1.MsgBol = WuLiaoCoffeeSel.Instance;
                clientList1.code = 10;
                clientList1.IsMake = false;
                SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList1)));
                IOMsg.Instance.AllBol = true;
                //Thread.Sleep(2000);
                GC.Collect();
                while (true)
                {
                    EditDeviceOrderStatus status = new EditDeviceOrderStatus();
                    status.orderGoodsId = list.id;
                    status.orderId = list.orderId;
                    status.status = 5;
                    string lists = JsonConvert.SerializeObject(status);
                    var ddd1 = HttpMsg.Instance.editDeviceOrderStatusMsg(lists);
                    if (ddd1 != null)
                    {
                        if (ddd1 != "")
                        {
                            var list10 = JsonConvert.DeserializeObject<ListMsg>(ddd1);
                            if (list10 != null)
                            {
                                if (list10.code == "0" || list10.code == "1")
                                {
                                    Console.WriteLine(DateTime.Now.ToString() + "  cx25 " + ddd1);
                                    break;
                                }
                            }
                            Console.WriteLine(DateTime.Now.ToString() + "  cx25 " + ddd1);
                        }

                    }
                    Thread.Sleep(100);
                }
                RobotOperate.CX_Start();
                Console.WriteLine(DateTime.Now.ToString() + "  cx5");
                if (RobotOperate.pstatus == JKTYPE.ProgramState.PROGRAM_RUNNING)
                {
                    if (WuLiaoCoffeeSel.Instance.RobotWarn != true)
                    {
                        WuLiaoCoffeeSel.Instance.RobotWarn = true;

                    }
                }
                else
                {
                    if (WuLiaoCoffeeSel.Instance.RobotWarn != false)
                    {
                        WuLiaoCoffeeSel.Instance.RobotWarn = false;

                    }
                }
                ClientList clientList2 = new ClientList();
                clientList2.MsgBol = WuLiaoCoffeeSel.Instance;
                clientList2.code = 2;
                SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList2)));
                //EditDeviceOrderStatus editDeviceOrder2 = new EditDeviceOrderStatus();
                //editDeviceOrder2.status = 5;
                //editDeviceOrder2.orderId = list.orderId;
                //editDeviceOrder2.orderGoodsId = list.id;
                //var ddd2 = JsonConvert.SerializeObject(editDeviceOrder2);
                //HttpMsg.Instance.editDeviceOrderStatusMsg(ddd2);
                isMake = true;
            }
            catch (Exception)
            {
                return;
            }
        }
        //裁剪图像
        public Bitmap CropImage(Bitmap originImage, Rectangle region)
        {
            Bitmap result = new Bitmap(region.Width, region.Height);
            Graphics graphics = Graphics.FromImage(result);
            graphics.DrawImage(originImage, new Rectangle(0, 0, region.Width, region.Height), region, GraphicsUnit.Pixel);
            return result;
        }
        public Bitmap DrawPic(Bitmap b, float angle)
        {
            //调用旋转函数
            Bitmap bb = RotateImg2(b, angle);
            int W = b.Width; //最大值
            int H = b.Height;//最大值
                             //旋转后图片大小
            int w = bb.Width;
            int h = bb.Height;
            //W×H图像大小背景图像坐标系到图像本身坐标系(旋转后图像）
            int move_x = (W - w) / 2;
            int move_y = (H - h) / 2;
            Bitmap aa = new Bitmap(W, H);//建立背景图片，在此基础上绘制
            for (int ii = 0; ii < W; ii++)
            {
                for (int jj = 0; jj < H; jj++)
                {
                    aa.SetPixel(ii, jj, System.Drawing.Color.FromArgb(255, 255, 255));
                }
            };
            Graphics g01 = Graphics.FromImage(aa);
            g01.TranslateTransform(move_x, move_y);//坐标系平移
            g01.DrawImage(bb, new PointF(0, 0));//坐标系平移后绘制图片

            int x = (W - w) / 2;
            int y = (H - h) / 2;
            //裁剪图片外围空白区域
            Rectangle cropRegion = new Rectangle(0, 0, W, H);
            Bitmap cc = CropImage(aa, cropRegion); //最终的图像数据
            return cc;
        }


        public Bitmap RotateImg2(Bitmap b, float angle)
        {
            angle = angle % 360;            //弧度转换
            double radian = angle * Math.PI / 180.0;
            double cos = Math.Cos(radian);
            double sin = Math.Sin(radian);
            //原图的宽和高
            int w = b.Width;
            int h = b.Height;
            //计算旋转后图片的大小
            int W = (int)(Math.Max(Math.Abs(w * cos - h * sin), Math.Abs(w * cos + h * sin)));
            int H = (int)(Math.Max(Math.Abs(w * sin - h * cos), Math.Abs(w * sin + h * cos)));
            //目标位图，也是在该图片上进行绘制
            Bitmap dsImage = new Bitmap(W, H);
            Graphics g = Graphics.FromImage(dsImage);
            g.InterpolationMode = InterpolationMode.Bilinear;
            g.SmoothingMode = SmoothingMode.HighQuality;
            //计算偏移量
            System.Drawing.Point Offset = new System.Drawing.Point((W - w) / 2, (H - h) / 2);
            //构造图像显示区域：让图像的中心与窗口的中心点一致
            Rectangle rect = new Rectangle(Offset.X, Offset.Y, w, h);
            System.Drawing.Point center = new System.Drawing.Point(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
            //参考系原点从图像左上角平移到中心，以实现图片绕中心旋转
            g.TranslateTransform(center.X, center.Y);
            //旋转参考系，相当于旋转图片
            g.RotateTransform(360 - angle);
            //恢复图像在水平和垂直方向的平移，坐标系原点恢复至旋转后坐标系的左上角
            g.TranslateTransform(-center.X, -center.Y);
            g.DrawImage(b, rect);
            //重至绘图的所有变换
            g.ResetTransform();
            g.Save();
            g.Dispose();
            //dsImage.Save("yuancd.png", System.Drawing.Imaging.ImageFormat.Png);
            return dsImage;
        }

        //public static Bitmap rotateImage(Bitmap b, float angle)
        //{
        //    try
        //    {
        //        //创建位图用于旋转图片
        //        Double tangle = angle * Math.PI / 180;
        //        Console.WriteLine(tangle);
        //        int r = (int)Math.Sqrt((b.Width * b.Width) + (b.Height * b.Height));
        //        int w = (int)(Math.Abs(b.Height * Math.Sin(tangle)) + Math.Abs(b.Width * Math.Cos(tangle)));
        //        int h = (int)(Math.Abs(b.Height * Math.Cos(tangle)) + Math.Abs(b.Width * Math.Sin(tangle)));
        //        Console.WriteLine(w);
        //        Console.WriteLine(h);
        //        Console.WriteLine(b.Width);
        //        Console.WriteLine(b.Height);
        //        //int h = b.Width;
        //        //int w = b.Height;
        //        Bitmap returnBitmap = new Bitmap(w, h);

        //        //初始化Graphics类
        //        Graphics g = Graphics.FromImage(returnBitmap);
        //        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
        //        //移动坐标原点到图片中心
        //        g.TranslateTransform((float)w / 2, (float)h / 2);
        //        //顺时针旋转对应angle的角度
        //        g.RotateTransform(angle);
        //        //移动坐标原地到原来的位置
        //        g.TranslateTransform(-(float)w / 2, -(float)h / 2);
        //        g.Clear(System.Drawing.Color.White);
        //        // 绘制旋转后的图片
        //        g.DrawImageUnscaled(image, (rotatedBmp.Width - image.Width) / 2, (rotatedBmp.Height - image.Height) / 2);
        //        //////构造图片
        //        ////g.DrawImage(b, new System.Drawing.Point((w - b.Width) / 2, (h - b.Height) / 2));

        //        g.Dispose();
        //        //返回位图
        //        return returnBitmap;
        //    }
        //    catch (Exception)
        //    {

        //        return null;
        //    }

        //}

        public static string ToBase64(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                String strbaser64 = Convert.ToBase64String(arr);
                return "data:image/jpeg;base64," + strbaser64;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
        public static Bitmap Base64StringToImage(string inputStr)
        {
            try
            {
                byte[] arr = Convert.FromBase64String(inputStr);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                ms.Close();
                return bmp;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                return null;
            }
        }
        /// <summary>
        /// 获取网络图片转换为base64
        /// </summary>
        /// <param name="url">网络图片路径   例：http://123.123.123.123/a.jpg</param>
        /// <returns></returns>
        public static string GetUrlToBase64(string url)
        {
#pragma warning disable CS0168 // 声明了变量，但从未使用过
            try
            {
                var base64String = "";
                HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
                HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;
                string base64sstr = string.Empty;
                using (Stream stream = webResponse.GetResponseStream())
                {
                    var mStream = new MemoryStream();

                    byte[] buffer = new byte[1024];
                    int byteCount;
                    do
                    {
                        byteCount = stream.Read(buffer, 0, buffer.Length);
                        mStream.Write(buffer, 0, byteCount);
                    } while (byteCount > 0);

                    mStream.Seek(0, SeekOrigin.Begin);
                    base64String = Convert.ToBase64String(mStream.ToArray());
                }
                //return base64String;
                WebClient mywebclient = new WebClient();
                byte[] Bytes = mywebclient.DownloadData(url);
                string Base64string = Convert.ToBase64String(Bytes);
                return base64String;
            }
            catch (Exception e)
            {
                return "";
            }
#pragma warning restore CS0168 // 声明了变量，但从未使用过
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            coffeeMsg.Instance.AllBol = false;
            Thread.Sleep(1000);
            CoffeeSerialPort.Instance.SerialSend(CoffeeMake.macchiato);
            Thread.Sleep(1000);
            coffeeMsg.Instance.AllBol = true;
            //string imgname = "";
            //Console.WriteLine("打印 " + DateTime.Now.ToString());
            //var base64url = GetUrlToBase64(@"https://jaka.motonbackend.top/public/uploads/20240709/2359a213a76b51bcb16609018f843f19.jpg");
            //Console.WriteLine("打印1" + DateTime.Now.ToString());
            //if (base64url != "")
            //{
            //    var bmp = Base64StringToImage(base64url);
            //    if (bmp != null)
            //    {
            //        var bmp145 = DrawPic(bmp, 145);//rotateImage(bmp, -145);
            //        if (bmp145 != null)
            //        {
            //            imgname = ToBase64(bmp145);
            //            Console.WriteLine(imgname);
            //            int width = 400;
            //            int height = 400;
            //            //  Bitmap bitmap = new Bitmap(width, height);
            //            //bitmap里面要有图片，自定义，我就不贴了
            //            //前一段为保存路径加文件名，后一段为保存格式，我这里保存为bmp格式，也可以为.jpeg或者.png之类的
            //            string path = "D:\\test.jpg";
            //            bmp145.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
            //        }
            //    }
            //}
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                IceMakingMsg.Instance.AllBol = false;
                Thread.Sleep(1000);
                IceMakingSerialPort.Instance.SerialSend(IceMakingModel.Instance.IceMaking);
                Thread.Sleep(1000);
                IceMakingMsg.Instance.AllBol = true;
            }
            catch (Exception)
            {
            }
        }
    }
    public class ListMsg
    {
        //"code":0,"msg":"Operation successfully","data":[]
        public string code { get; set; }
        public object msg { get; set; }
        public object data { get; set; }
    }
}
